package com.czy.daishusys.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.czy.daishusys.R;
import com.czy.daishusys.adapter.ExpandableStaffAdapter;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.StoreBooks;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * * Created by hedepu on 2017-11-30
 * 员工结构
 * 注释代码为去除搜索功能
 **/
public class StoreContactsListActivity extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.relat_list)
    RecyclerView relatList;
    //    @BindView(R.id.et_search_contacts)
//    EditText etSearchContacts;
//    @BindView(R.id.img_search_contacts)
//    ImageView imgSearchContacts;
    private List<StoreBooks> storeGroupsData = new ArrayList<>();
    //    private List<StoreBooks> storeAllGroupsData = new ArrayList<>();
    private ArrayList<MultiItemEntity> list = new ArrayList<>();
    private ExpandableStaffAdapter adapter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_store_contacts_list;
    }

    @Override
    protected void initInjector() {
        if (PhoneUtils.isEmpty(getIntent().getStringExtra("storeId"))) {
            PhoneUtils.ShowToastMessage(this, getResources().getString(R.string.finish_parameter_anomaly));
            finish();
        }
    }

    @Override
    protected void initViews() {
        toolbarTitle.setText(R.string.store_contacts_title);
        relatList.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.shape_line_divider_decoration));
        relatList.addItemDecoration(dividerItemDecoration);

        adapter = new ExpandableStaffAdapter(list);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //判断是分类子项，跳转员工详情
                if (adapter.getData().get(position) instanceof StoreBooks.StoreBooksDetail) {
                    StoreBooks.StoreBooksDetail storeBooksDetail = (StoreBooks.StoreBooksDetail) adapter.getData().get(position);
                    startActivity(new Intent(StoreContactsListActivity.this, ContactsDetailActivity.class).putExtra("storeEmployeesId", storeBooksDetail.getStoreEmployeesId() + ""));
                }
            }
        });
        relatList.setAdapter(adapter);
//        etSearchContacts.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//
//                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
//                /*隐藏软键盘*/
//                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//                    if (inputMethodManager.isActive()) {
//                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
//                    }
//                    CharSequence searchKeyword = etSearchContacts.getText().toString().trim();
//                    //输入框位空展示全部
//                    if (etSearchContacts.getText().toString().trim() == null || TextUtils.isEmpty(etSearchContacts.getText().toString().trim())) {
//                        generateData();
//                        setAdapter();
//                        // 输入框不为空，检索包含输出内容的员工
//                    } else {
//                        for (int i = 0; i < storeGroupsData.size(); i++) {
//                            storeGroupsData.get(i).getSubItems().clear();
//                            storeGroupsData.get(i).setExpanded(false);
//                            for (int j = 0; j < storeGroupsData.get(i).getEmployeeList().size(); j++) {
//
//                                if (storeGroupsData.get(i).getEmployeeList().get(j).getEmployeesName().contains(searchKeyword)) {
//                                    storeGroupsData.get(i).addSubItem(storeGroupsData.get(i).getEmployeeList().get(j));
////                                    storeBooks.getList().add(storeAllGroupsData.get(i).getList().get(j));
//                                }
//                            }
//
//                        }
//
//                        setAdapter();
//                    }
//                    return true;
//                }
//                return false;
//
//
//            }
//        });
//        etSearchContacts.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (etSearchContacts.getText().toString().trim() == null || TextUtils.isEmpty(etSearchContacts.getText().toString().trim())) {
//                    generateData();
//                    setAdapter();
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
//        shareAddContactSidebar.setOnTouchingLetterChangedListener(new IndexBar.OnTouchingLetterChangeListener() {
//            @Override
//            public void onTouchingLetterChanged(String s) {
//                dialogLetterHintTextview.setVisibility(View.VISIBLE);
//                dialogLetterHintTextview.setText(s);
//                for (Integer position : mHeaderList.keySet()) {
//                    if (mHeaderList.get(position).equals(s)) {
//                        mLayoutManager.scrollToPositionWithOffset(position, 0);
//                        return;
//                    }
//                }
//            }
//
//            @Override
//            public void onTouchingStart(String s) {
//                dialogLetterHintTextview.setVisibility(View.VISIBLE);
//                dialogLetterHintTextview.setText(s);
//            }
//
//            @Override
//            public void onTouchingEnd(String s) {
//                dialogLetterHintTextview.setVisibility(View.GONE);
//            }
//        });
    }

    @Override
    protected void updateViews() {
        postUserDetails();
    }

    //获取员工组成
    public void postUserDetails() {
        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSession(this));
        params.put("storeId", getIntent().getStringExtra("storeId"));
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_USER_INFO_DTOREEMPS)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new CallBack<String>() {
                    @Override
                    public void onStart() {
                        mMProgressDialog.show(getResources().getString(R.string.loading_text));
                    }

                    @Override
                    public void onCompleted() {
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("EasyHttp", result);
                        String data = PhoneUtils.checkResponseFlag(StoreContactsListActivity.this, result);
                        if (data != null && !"{}".equals(data)) {
//                            JSONObject jsonObject = null;
//                            try {
//                                jsonObject = new JSONObject(data);
//                                List<String> list = new ArrayList<>();
//                                Iterator<String> keys = jsonObject.keys();
//                                String key;
//                                while (keys.hasNext()) {
//                                    key = keys.next();
//                                    list.add(jsonObject.getString(key));
//                                }
//                                for (int i = 0; i < list.size(); i++) {
//                                    StoreBooks tmpStoreBooks = new Gson().fromJson(list.get(i).toString(), StoreBooks.class);
//                                    storeGroupsData.add(tmpStoreBooks);
////                                    storeAllGroupsData.add(tmpStoreBooks);
//                                }
//
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
                            storeGroupsData = GsonUtils.fromJsonList(data, StoreBooks.class);
                            generateData();
                            setAdapter();


                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();

                    }
                });


    }

    public void setAdapter() {
        list.clear();
        list.addAll(storeGroupsData);
        adapter.setNewData(list);
        adapter.expandAll();

    }

    //返回数据处理
    private ArrayList<MultiItemEntity> generateData() {

        for (StoreBooks storeBooks : storeGroupsData) {
            storeBooks.setExpanded(false);
            if (storeBooks.getSubItems() != null && storeBooks.getSubItems().size() > 0)
                storeBooks.getSubItems().clear();
            storeBooks.addAllSubItem(storeBooks.getEmployeeList());
        }
        ArrayList<MultiItemEntity> res = new ArrayList<>();
        res.addAll(storeGroupsData);
        return res;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
